package com.dragon.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dragon.pojo.Result;
import com.dragon.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import java.io.IOException;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 如果处理器是静态资源处理器，直接放行
        if (handler instanceof ResourceHttpRequestHandler) {
            log.info("请求是静态资源: {}，直接放行。", request.getRequestURI());
            return true;
        }

        // 获取请求头中的令牌
        String jwt = request.getHeader("Accept-token");

        // 判断token是否存在
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空，用户未登录");
            Result error = Result.error("NOT_LOGIN");
            //手动转换对象--json->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        // 解析token
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            request.setAttribute("claims", claims);
        } catch (Exception e) {
            log.error(String.valueOf(e));
            log.info("解析令牌失败，用户令牌无效");
            Result error = Result.error("NOT_LOGIN");
            //手动转换对象--json->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        // 放行
        log.info("令牌合法，放行用户id:{}", JwtUtils.parseJWT(jwt).get("id"));
        return true;
    }
}
